package com.net.server;

import com.pojo.ClientRunTimeInfo;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName ConnectManager
 * @Description TODO
 * @Author zhuchen216628
 * @Date 2018/9/28 15:08
 * @Version 1.0
 **/
@Component
public class ConnectManager implements InitializingBean{

    private static Logger logger = LoggerFactory.getLogger(ConnectManager.class);

    public Map<Channel, ClientRunTimeInfo> connectMap = new ConcurrentHashMap<Channel, ClientRunTimeInfo>();

//    public ConnectManager(){
//        System.out.println("ConnectManager");
//    }

    public void afterPropertiesSet(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    logger.info("机器连接数：" + connectMap.size());
                    for (Map.Entry<Channel, ClientRunTimeInfo> entry : connectMap.entrySet()) {
                        Channel channel = entry.getKey();
                        ClientRunTimeInfo clientRunTimeInfo = entry.getValue();
                        logger.info("连接服务器：{} ，状况：{}" ,channel.remoteAddress(),clientRunTimeInfo.toString());
                    }
                }
            }
        }).start();
    }

    public Map<Channel, ClientRunTimeInfo> getConnectMap() {
        return connectMap;
    }

    public void setConnectMap(Map<Channel, ClientRunTimeInfo> connectMap) {
        this.connectMap = connectMap;
    }

    public ClientRunTimeInfo chooseDevice() {
        for (Map.Entry<Channel, ClientRunTimeInfo> entry : connectMap.entrySet()) {
            Channel channel = entry.getKey();
            ClientRunTimeInfo clientRunTimeInfo = entry.getValue();
            return clientRunTimeInfo;
        }
        return null;
    }
}
